package com.chenyun.common.utils;

import com.chenyun.common.exceptions.BusinessException;
import org.apache.commons.collections4.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.HashSet;
import java.util.Set;

/**
 * ValidationUtils：
 * Description:
 *
 * @author: Lonni
 * @date: 2022/8/4 0004 15:24
 */
public class ValidationUtils {
    private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
    /**
     * 参数校验
     *
     * @param paramObject 需要校验的参数
     */
    public static void validateObject(Object paramObject) {
        Validator validator = VALIDATOR_FACTORY.getValidator();
        Set<ConstraintViolation<Object>> validateResult = validator.validate(paramObject);
        if (CollectionUtils.isEmpty(validateResult)) {
            return;
        }

        StringBuilder errorMessageSb = new StringBuilder();
        for (ConstraintViolation<Object> violation : validateResult) {
            errorMessageSb.append(violation.getMessage()).append(";");
        }
        throw new BusinessException( errorMessageSb.toString());
    }

    /**
     * 参数校验【支持分组校验】
     *
     * @param paramObject 需要校验的参数
     * @param classes     具体的分组
     */
    public static void validateObject(Object paramObject, Class<?> groups) {
        Validator validator = VALIDATOR_FACTORY.getValidator();
        Set<ConstraintViolation<Object>> validateResult = validator.validate(paramObject, groups);
        if (CollectionUtils.isEmpty(validateResult)) {
            return;
        }

        Set<String> errorMsgSet = new HashSet<>();
        for (ConstraintViolation<Object> violation : validateResult) {
            errorMsgSet.add(violation.getMessage());
        }
        throw new BusinessException( String.join(",", errorMsgSet));
    }

    private ValidationUtils() {

    }


}
